<?php
/**
 * 
 * @author jing
 * 2014.12.2
 *
 */
class AccountController extends Controller {
	
	private $push_logo = "/common/clientapi/images/50.png";
	private $uploadpath;
	
	public function __construct() {
		parent::__construct ();
		$this->view->web_host = $this->getRequest ()->hostUrl;
		$this->view->web_app_url = $this->getRequest ()->hostUrl . "/index.php";
		$this->uploadpath=$this->getRequest ()->hostUrl.$this->push_logo;
	}
	
	/**
	 * 登录
	 * 模式1默认
	 * http://119.254.108.124:10023/clientapi.php/Account/Login/phone/18202565729/password/123456/osType/1/token/23sf/isStudent/1
	 */
	public function Login() {
		$style = $this->getRequest ()->get ( "style" );//后期扩充
		$username = $this->getRequest ()->get ( "phone" );
		($ClientId = $this->getRequest ()->get ( "ClientId" ))|| ($ClientId = "0") ;
		($DeviceToken = $this->getRequest ()->get ( "DeviceToken" ))||($DeviceToken = "0");//安卓可不传
		($password = $this->getRequest ()->get ( "password" )) ||  ($password = "0" );
		$osType = $this->getRequest ()->get ( "osType" );
		$isStudent = $this->getRequest ()->get ( "isStudent" ) ? $this->getRequest ()->get ( "isStudent" ) : '0'  ;
		if ($username && $osType) {
			$user = new user ();
			$userinfo = $user->authUser ( $username, $password);
			$data = array ();
			if ($userinfo ["result"] > 0) {
				// 判断是否从教师端登录学生账号, 或者从学生端登录教师账号, 此时返回登录失败
				if ($isStudent && $userinfo ["userinfo"] ["role_id"] != RoleCodeEnum::ROLE_STUDENT) {
					$this->view->setState ( "-2" );
					$this->view->setStatus ( "0" );
					$this->view->setMsg ( "此用户身份为教师，请在教师端登录" );
					$this->view->setData ( ( object ) null );
					$this->view->display ( "json" );
					return;
				} else if (! $isStudent && $userinfo ["userinfo"] ["role_id"] == RoleCodeEnum::ROLE_STUDENT) {
					$this->view->setState ( "-1" );
					$this->view->setStatus ( "0" );
					$this->view->setMsg ( "此用户身份为学生，请在学生端登录" );
					$this->view->setData ( ( object ) null );
					$this->view->display ( "json" );
					return;
				}
				if ($ClientId && $osType){
					$user->setPhoneInfoClear($ClientId, $osType, $device = NULL, $token = NULL) ;
				}
				
				//透传
				$phone_info = $user->getPhoneInfo($userinfo ["userinfo"] ["id"]);
				if ($ClientId && $phone_info['clientid'] && $ClientId != $phone_info['clientid']){
					if ($phone_info && $phone_info['token']){
						$target = array(
								"type"=>$phone_info['type'],
								"ClientID"=>$phone_info['clientid'],
								"DeviceToken"=>$phone_info['devicetoken'],
						);
						$content = array(
								"info"=>"单点登录",//透传
								"title"=>'UDO学生端',
								"text"=>'你的账户已在其他设备登录，如非本人操作请确认是否密码丢失',
								"logo_url"=>$this->uploadpath,
						);
						if ($osType == 1){
							$this->push->pushToSingle($target, $content);
							$this->push->IGtTransmission($content['info'],$phone_info['clientid']);
						}else{
							$this->push->pushToSingleforIos($target, $content);
						}
					}
					$session = $this->getApp ()->loadUtilClass ( "SessionUtil" );
					$session->clear ();
					//$this->Logout();
				}
				
				$data ["userID"] = $userinfo ["userinfo"] ["id"];
				$data ["name"] = $userinfo ["userinfo"] ["name"];
				$data ["role"] = $userinfo ["userinfo"] ["role_id"];
				
				//统计用户未读消息的条数
				$message=new message();
				$data ["message_num"] =$message->getUserfulMessageTotal($data ["userID"]);
				
				$session = $this->getApp ()->loadUtilClass ( "SessionUtil" );
				$session->set ( "session_userid", $userinfo ["result"] );
				$token = md5($userinfo ["result"].time().rand(100000, 999999)) ;
				$session->set ( "token_id", $token);
				
				$user->setPhoneInfo ( $userinfo ["result"], $osType, $token,$ClientId,$DeviceToken);
				$this->view->setState ( "1" );
				$this->view->setStatus ( "0" );
				$this->view->setMsg ( "登录成功!" );
				$this->view->setData ( $data );
				$this->view->display ( "json" );
			} else {
				if ($userinfo ["result"] == - 1) {
					$this->view->setState ( "-3" );
					$this->view->setStatus ( "0" );
					$this->view->setData ( ( object ) null );
					$this->view->setMsg ( "密码错误，再试一次吧~" );
					$this->view->display ( "json" );
				}elseif ($userinfo ["result"] == -3){
					$this->view->setState ( "-5" );
					$this->view->setStatus ( "0" );
					$this->view->setData ( ( object ) null );
					$this->view->setMsg ( "首次登录请设置密码" );
					$this->view->display ( "json" );
				} else {
					$this->view->setState ( "-4" );
					$this->view->setStatus ( "0" );
					$this->view->setData ( ( object ) null );
					$this->view->setMsg ( "只有新东方才能登录噢" );
					$this->view->display ( "json" );
				}
			}
		}else {
			$this->view->setState ( "0" );
			$this->view->setMsg ( "参数缺失!" );
			$this->view->setStatus ( "0" );
			$this->view->setData ( ( object ) null );
			$this->view->display ( "json" );
		}
	}
	
	/**
	 * 注销
	 */
	public function Logout() {
		$userInfo = $this->getData ( "userinfo" );
		if ($userInfo) {
			$user = new user ();
			$user->setPhoneInfo ( $userInfo ["id"] );
		}
		$session = $this->getApp ()->loadUtilClass ( "SessionUtil" );
		$session->clear ();
		$this->view->setMsg ( "注销成功" );
		$this->view->setState ( "1" );
		$this->view->setStatus ( "0" );
		$this->view->setData ( ( object ) null );
		$this->view->display ( "json" );
	}
	
	/**
	 * 生成验证码, 用于找回密码,修改密码,首次登录
	 */
	public function Getcode() {
		$phoneNum = $this->getRequest ()->get ( "phone" );
		$user_new = $this->getRequest ()->get("userNew");
		
		$isStudent = $this->getRequest ()->get ( "isStudent" ) ? $this->getRequest ()->get ( "isStudent" ) : '0';
		if ($phoneNum){
			$user = new user ();
			$user_infos = $user->authUser ( $phoneNum );
			if ($user_new){
				if ($user_infos ["result"] == -2){
					$this->view->setState ( "-5" );
					$this->view->setData ( ( object ) null );
					$this->view->setMsg ( "亲，只有新东方用户才能登录" );
					$this->view->display ( "json" );
					return ;
				}else if($user_infos ["result"] != -3){
					$this->view->setState ( "-7" );
					$this->view->setData ( ( object ) null );
					$this->view->setMsg ( "请直接输入密码登录，非首次登录" );
					$this->view->display ( "json" );
					return ;
				}
			}else{
				if ($user_infos ["result"] == -2){
					$this->view->setState ( "-5" );
					$this->view->setData ( ( object ) null );
					$this->view->setMsg ( "亲，只有新东方用户才能登录" );
					$this->view->display ( "json" );
					return ;
				}else if($user_infos ["result"] == -3){
					$this->view->setState ( "-7" );
					$this->view->setData ( ( object ) null );
					$this->view->setMsg ( "首次登录，请先设置密码" );
					$this->view->display ( "json" );
					return ;
				}
			}
			
			$userinfo = $user->getUserByPhone ( $phoneNum );
			if ($userinfo){
				// 判断是否从教师端登录学生账号, 或者从学生端登录教师账号, 此时返回登录失败
				if ($isStudent && $userinfo ["role_id"] != RoleCodeEnum::ROLE_STUDENT) {
					$this->view->setState ( "-2" );
					$this->view->setData ( ( object ) null );
					$this->view->setMsg ( "此用户身份为教师，请在教师端登录" );
					$this->view->display ( "json" );
					return;
				} else if (! $isStudent && $userinfo  ["role_id"] == RoleCodeEnum::ROLE_STUDENT) {
					$this->view->setState ( "-1" );
					$this->view->setData ( ( object ) null );
					$this->view->setMsg ( "此用户身份为学生，请在学生端登录" );
					$this->view->display ( "json" );
					return;
				}
				$session = $this->getApp ()->loadUtilClass ( "SessionUtil" );
				// 生成验证码
				list ( $msec, $sec ) = explode ( ' ', microtime () );
				srand ( $sec );
				$code = rand ( 100000, 999999 );
				$session->set ( "code", $code );
				
				$stringUtil = $this->getApp ()->loadUtilClass ( "StringUtil" );
				if ($stringUtil->is_phone ( $phoneNum )) {
					require_once "been/Util/SmsUtil.php";
					$sms_conf = $this->getApp()->loadConf("sms");
					$Sms = new SmsUtil($sms_conf);
					$data = array($code ,"5");
					$result = $Sms->sendTemplateSMS($phoneNum, $data, 9188);
					if ($result ["state"] == 0 && $result ["dateCreated"] ) { // 发送成功
						$session->set ( "account_phone", $phoneNum );
						$this->view->setState ( "1" );
						$this->view->setData ( ( object ) null );
						$this->view->setMsg ( "信息成功发送，请等待~" );
						$this->view->display ( "json" );
						return ;
					} else {
						$this->view->setState ("-3");
						$this->view->setData ( ( object ) null );
						$this->view->setMsg ( "信息发送失败!(" . $result ["state"] . ":" . $result ["msg"] . ")" );
						$this->view->display ( "json" );
						return ;
					}
				} else {
					// phoneNum参数不是手机
					$this->view->setMsg ( "手机号码格式错误" );
					$this->view->setState ( "-4" );
					$this->view->setData ( ( object ) null );
					$this->view->display ( "json" );
					return ;
				}	
			}else {
				$this->view->setState ( "-5" );
				$this->view->setData ( ( object ) null );
				$this->view->setMsg ( "亲，只有新东方用户才能登录" );
				$this->view->display ( "json" );
				return ;
			}			
		} else {
			// 没有phoneNum参数
			$this->view->setMsg ( "参数缺失" );
			$this->view->setData ( ( object ) null );
			$this->view->setState ( "0" );
			$this->view->display ( "json" );
			return ;
		}
	}
	
	/**
	 * 生成语音验证码, 用于找回密码,修改密码,首次登录
	 */
	public function Getcodebyvoice() {
		$phoneNum = $this->getRequest ()->get ( "phone" );
		$isStudent = $this->getRequest ()->get ( "isStudent" ) ? $this->getRequest ()->get ( "isStudent" ) : '0';
		if ($phoneNum){
			$user = new user ();
			$userinfo = $user->getUserByPhone ( $phoneNum );
			if ($userinfo){
				// 判断是否从教师端登录学生账号, 或者从学生端登录教师账号, 此时返回登录失败
				if ($isStudent && $userinfo ["role_id"] != RoleCodeEnum::ROLE_STUDENT) {
					$this->view->setState ( "-2" );
					$this->view->setData ( ( object ) null );
					$this->view->setMsg ( "此用户身份为教师，请在教师端登录" );
					$this->view->display ( "json" );
					return;
				} else if (! $isStudent && $userinfo  ["role_id"] == RoleCodeEnum::ROLE_STUDENT) {
					$this->view->setState ( "-1" );
					$this->view->setData ( ( object ) null );
					$this->view->setMsg ( "此用户身份为学生，请在学生端登录" );
					$this->view->display ( "json" );
					return;
				}
				$session = $this->getApp ()->loadUtilClass ( "SessionUtil" );
				// 生成验证码
				if ($session->get ( "code" )){
					$code = $session->get ( "code" );
				}else {
					list ( $msec, $sec ) = explode ( ' ', microtime () );
					srand ( $sec );
					$code = rand ( 100000, 999999 );
					$session->set ( "code", $code );
				}
	
				$stringUtil = $this->getApp ()->loadUtilClass ( "StringUtil" );
				if ($stringUtil->is_phone ( $phoneNum )) {
					require_once "been/Util/SmsUtil.php";
					$sms_conf = $this->getApp()->loadConf("sms");
					$Sms = new SmsUtil($sms_conf);
					$data = array($code ,"5");
					$result = $Sms->voiceVerify($code, 2, $phoneNum, "400666666",
					'');
					if ($result ["state"] == 0 && $result ["dateCreated"] ) { // 发送成功
						$session->set ( "account_phone", $phoneNum );
						$this->view->setState ( "1" );
						$this->view->setData ( ( object ) null );
						$this->view->setMsg ( "信息成功发送，请等待~" );
						$this->view->display ( "json" );
						return ;
					} else {
						$this->view->setState ("-3");
						$this->view->setData ( ( object ) null );
						$this->view->setMsg ( "信息发送失败!(" . $result ["state"] . ":" . $result ["msg"] . ")" );
						$this->view->display ( "json" );
						return ;
					}
				} else {
					// phoneNum参数不是手机
					$this->view->setMsg ( "手机号码格式错误" );
					$this->view->setData ( ( object ) null );
					$this->view->setState ( "-4" );
					$this->view->display ( "json" );
					return ;
				}
			}else {
				$this->view->setState ( "-5" );
				$this->view->setData ( ( object ) null );
				$this->view->setMsg ( "亲，只有新东方用户才能登录" );
				$this->view->display ( "json" );
				return ;
			}
		} else {
			// 没有phoneNum参数
			$this->view->setMsg ( "参数缺失" );
			$this->view->setState ( "0" );
			$this->view->setData ( ( object ) null );
			$this->view->display ( "json" );
			return ;
		}
	}
	
	
	
	/**
	 * 核对验证码
	 */
	public function Checkcode() {
		$phoneNum = $this->getRequest ()->get ( "phone" );
		$verifyCode = $this->getRequest ()->get ( "code" );
		if ($phoneNum && $verifyCode) {
			$session = $this->getApp ()->loadUtilClass ( "SessionUtil" );
			$code = $session->get ( "code" );
			if ($session->get ( "account_phone") != $phoneNum ){
				$this->view->setState ( "-2" );
				$this->view->setMsg ( "请输入正确的手机号" );
				$this->view->setData ( ( object ) null );
				$this->view->display ( "json" );
				return ;
			}
			
			if ($code == $verifyCode) {
				$session->set ( "findpw_account", $phoneNum );
				$this->view->setState ( "1" );
				$this->view->setMsg ( "验证码正确!" );
				$session->del("code");
			} else {
				$this->view->setState ( "-3" );
				$this->view->setMsg ( "您输入验证码不正确~\n请仔细输入或者再次点击获取新的验证码~" );
			}
		} else {
			// 没有phoneNum, verifyCode参数
			$this->view->setMsg ( "参数缺失" );
			$this->view->setState ( "0" );
		}
		$this->view->setData ( ( object ) null );
		$this->view->display ( "json" );
	}
	/**
	 * 重置密码/找回密码/设置密码
	 */
	public function Resetpassword() {
		$phoneNum = $this->getRequest ()->get ( "phone" );
		$password = $this->getRequest ()->get ( "password" );
		$session = $this->getApp ()->loadUtilClass ( "SessionUtil" );
		if (! ($phoneNum && $password)) {
			$this->view->setMsg ( "参数缺失" );
			$this->view->setState ( "0" );
			$this->view->setStatus ( "0" );
			$this->view->setData ( ( object ) null );
			$this->view->display ( "json" );
			return ;
		}
		
		if (! $session->get ( "findpw_account" )) {//如果没有获取找回密码的账号
			$this->view->setMsg ( "请获取验证码" );
			$this->view->setState ( "-3" );
			$this->view->setStatus ( "0" );
			$this->view->setData ( ( object ) null );
			$this->view->display ( "json" );
		} else {
			$user = new user ();
			$userinfo = $user->getUserByPhone ( $phoneNum );
			
			if (! $userinfo) {
				$this->view->setMsg ( "账号错误" );
				$this->view->setState ( "-1" );
				$this->view->setStatus ( "0" );
				$this->view->setData ( ( object ) null );
				$this->view->display ( "json" );
			} else {
				if ($user->setPw ( $userinfo ['id'], $password )) {
					$this->view->setMsg ( "密码重置成功!" );
					$this->view->setState ( "1" );
					$this->view->setStatus ( "0" );
					$this->view->setData ( ( object ) null );
					
				} else {
					$this->view->setMsg ( "密码重置失败!" );
					$this->view->setState ( "-2" );
					$this->view->setStatus ( "0" );
					$this->view->setData ( ( object ) null );
				}
				$this->view->display ( "json" );
			}
		}
	}
	
	/**
	 * 5.1 获取个人资料
	 *
	 */
	public function GetPersonDetail() {
		$data = array ();
		$userinfo = $this->getData ( 'userinfo' );
		$userID = $userinfo ['id'];
		$uuser = new user ();
		$list = $uuser->getUserInfo ( $userID );
		if ($list) {
			$data['id'] =  $userinfo ['id'];
			$data['name'] = $list['name']; 
			$data['phone'] = $list['phone']; 
			$data['mail'] = $list['mail'];
			$data['qq'] = $list['qq'];
			$data['create_time'] = $list['create_time'];
			$data['sentence'] = $list['sentence'];
			($list['icon'] = $list['icon']) || ($list['icon'] = "1");
			$icon = $uuser->getUserIcon($list['icon']);		
			$qiniu_path=$this->_app->getData("qiniu_path");
			//$data['icon'] = $qiniu_path["qiniu_path_image"].$icon['name']."?imageView2/1/w/100/h/100";
			$data['icon'] = $qiniu_path["qiniu_path_image"].$icon['name'];
			$this->view->setState ( "1" );
			$this->view->setMsg ( "获取个人资料成功~" );
		} else {
			$this->view->setState ( "0" );
			$data = ( object ) null;
			$this->view->setMsg ( "访问出错~" );
		}
		$this->view->setData ( $data );
		$this->view->display ( "json" );
	}
	
	/**
	 * 5.2 设置资料
	 *
	 * @author jing
	 */
	public function SavePersonDetail() {
		$userinfo = $this->getData ( 'userinfo' );
		$userID = $userinfo ['id'];
		($name = $this->getRequest ()->get ( "name" ))||($name = "0");
		($mail = $this->getRequest ()->get ( "mail" ))||($mail = "0");
		($qq = $this->getRequest ()->get ( "qq" ))||($qq = "0");
		($sentence = $this->getRequest ()->get ( "sentence" ))||($sentence = "0");
		$sentence = urldecode($sentence);
		$name = urldecode($name);
		$mail = urldecode($mail);
// 		if ($name && $mail && $sentence && $qq) {
			$uuser = new user ();
			$result = $uuser->SavePersonDetail ( $userID, $name, $mail,$qq,$sentence);
			if ($result) {
				$this->view->setState ( "1" );
				$this->view->setMsg ( "设置成功~" );
			} else {
				$this->view->setState ( "-1" );
				$this->view->setMsg ( "设置失败~" );
			}
// 		} else {
// 			$this->view->setState ( "0" );
// 			$this->view->setMsg ( "参数缺失！" );
// 		}
		$this->view->display ( "json" );
	}
	
	/**
	 * 修改头像
	 */
	public function Updateicon() {
		$msg="";
		$userinfo = $this->getData ( 'userinfo' );
		$userID = $userinfo ['id'];
		$this->getApp()->loadUtilClass("UploadUtil");
		$upPara=array(
				'allowType'=>array("jpg","jpeg","gif","png","bmp","*"),//图片格式另定
				'maxsize'=>"2000000000",//大小限制2M
				'israndname'=>true,
				'filepath'=>"common/upload/image/"
		);
		$up=new uploadutil($upPara);
		if($up->uploadFile("image")){
			$msg.="上传图片成功！";
			$image=new image();
			$imageName=$up->getNewFileName();
			$uuser=new user();
			$image_id=$image->addImage($imageName);
			if( $image_id ){
				if($uuser->Updateicon($userID, $image_id)){
					//$msg.="保存反馈到数据库成功！";
					$msg.="";
					$this->view->setState("1");
				}else {
					$this->view->setState("-1");
					//$msg="保存反馈到数据库失败！";
					$msg="";
				}
			}else{
				//$msg="保存图片到数据库失败！";
				$msg="";
			}
				
		}else{
			$this->view->setState("-2");
			$up_error=$up->getErrorMsg();
			if(is_array($up_error)){
				$up_errors=join(",",$up_error);
				$msg.="上传图片失败！".$up_errors;
			}else
				$msg.="上传图片失败！".$up->$up_error;
		}
		$this->view->setMsg($msg);
		$this->view->display ( "json" );
	}
	
	/**
	 * 修改密码
	 */
	public function Resetpsw(){
		($old_psw = $this->getRequest ()->get ( "old_psw" ))||($old_psw = "0");
		($new_psw = $this->getRequest ()->get ( "new_psw" ))||($new_psw = "0");
		if ($new_psw && $old_psw){
			$userinfo = $this->getData ( 'userinfo' );
			$userID = $userinfo ['id'];
			$old_pwd = md5(md5($old_psw.$userinfo['salt']));
			if ($old_pwd == $userinfo['password']){
				$user = new user();
				if ($user->setPw ( $userinfo ['id'], $new_psw )) {
					$this->view->setMsg ( "密码重置成功!" );
					$this->view->setState ( "1" );
					$this->view->setStatus ( "0" );
					$this->view->setData ( ( object ) null );
						
				} else {
					$this->view->setMsg ( "密码重置失败!" );
					$this->view->setState ( "-2" );
					$this->view->setStatus ( "0" );
					$this->view->setData ( ( object ) null );
				}
				$this->view->display ( "json" );
			}else {
				$this->view->setMsg ( "原始密码输入错误" );
				$this->view->setState ( "-1" );
				$this->view->setData ( ( object ) null );
				$this->view->display ( "json" );
				return ;
			}
		}else {
			$this->view->setMsg ( "参数缺失" );
			$this->view->setState ( "0" );
			$this->view->setData ( ( object ) null );
			$this->view->display ( "json" );
			return ;
		}
	}
	/**
	 * 在登录状态获取  IOS设备信息
	 */
	public function Getdeviceinfo(){
		($userId = $this->getRequest ()->get ( "userId" ))|| ($userId = "0") ;
		($ClientId = $this->getRequest ()->get ( "ClientId" ))|| ($ClientId = "0") ;
		($DeviceToken = $this->getRequest ()->get ( "DeviceToken" ))||($DeviceToken = "0");//安卓可不传
		$osType = $this->getRequest ()->get ( "osType" );
		$user = new user ();
		if ($userId && $ClientId && $DeviceToken){
			$phone_info = $user->getPhoneInfo($userId);
			if($phone_info['clientid'] && $phone_info['devicetoken'] && $ClientId == $phone_info['clientid'] && $DeviceToken == $phone_info['devicetoken'] && $osType == $phone_info['type'] ){
				$this->view->setMsg ( "正常登录" );
				$this->view->setState ( "1" );
				$this->view->setData ( ( object ) null );
				$this->view->display ( "json" );
				return ;
			}else {
				$this->view->setMsg ( "你的账户已在其他设备登录，如非本人操作请确认是否密码丢失" );
				$this->view->setState ( "0" );
				$this->view->setData ( ( object ) null );
				$this->view->display ( "json" );
				return ;
			}
		}else {
			$this->view->setMsg ( "参数缺失" );
			$this->view->setState ( "-1" );
			$this->view->setData ( ( object ) null );
			$this->view->display ( "json" );
			return ;
		}
	}
}